import logging
from dataclasses import dataclass

from src.application.order.converters import convert_order_entity_to_dto
from src.application.order.uow import OrderUoW
from src.domain.order.entities.allowed_ip import AllowedIpEntity

logger = logging.getLogger(__name__)


@dataclass(frozen=True)
class AddAllowedIpToOrder:
    order_id: int
    allowed_ip_id: int


class AddAllowedIpToOrderHandler:
    """Добавляем allowed ip в заказ"""

    def __init__(
        self,
        *,
        uow: OrderUoW,
    ) -> None:
        self._uow = uow

    async def __call__(self, command: AddAllowedIpToOrder) -> None:
        allowed_ip = await self._uow  # TODO Добавить получение Allowed_ip Entity
        allowed_ip = AllowedIpEntity.create_allowed_ip(tg_user_id=user_id, ip_address=command.ip_address)

        try:
            await self._uow.user_repo.update_user(user)
        except Exception as err:
            await self._uow.rollback()
            raise err

        await self._uow.commit()

        logger.info(f"Order №{command.order_id} was archived")

        order_dto = convert_order_entity_to_dto(order)

        return order_dto
